<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="自定义名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入自定义名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
  
      <el-form-item label="TLS 验证" prop="tlsVerify">
        <el-select v-model="queryParams.tlsVerify" placeholder="请选择TLS 验证" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['docker:config:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['docker:config:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table stripe v-loading="loading" :data="configList" :header-cell-style="{'text-align':'left'}" @expand-change="handledetail">
      <el-table-column type="expand" >
        <template slot-scope="props">
          <el-form label-width="29.5%" label-position="center" inline class="table-expand">
            <el-col :span="24">
              <el-form-item label="自定义名称">
                <span>{{ props.row.name }}</span> 
              </el-form-item>   
              <el-form-item label="Docker 名称">
                <span>{{ props.row.detail.localdomain }}</span>
              </el-form-item>  
              <el-form-item label="OS版本">
                <span>{{ props.row.detail.operatingSystem }}</span>
              </el-form-item>
              <el-form-item label="镜像仓库地址">
                <el-tooltip class="item" effect="dark" :content="props.row.detail.mirrors">
                  <span class="text">{{ props.row.detail.mirrors }}</span>
                </el-tooltip>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="CPU">
                <span>{{ props.row.detail.cpu }}</span>
              </el-form-item>
              <el-form-item label="内存">
                <span>{{ props.row.detail.memTotal }}</span>
              </el-form-item>
            </el-col>
            <el-form-item label="总的容器数">
              <span>{{ props.row.detail.containers }}</span>
            </el-form-item>
            <el-form-item label="运行容器数">
              <span>{{ props.row.detail.containersRunning }}</span>
            </el-form-item>
            <el-form-item label="停止容器数">
              <span>{{ props.row.detail.containersStopped }}</span>
            </el-form-item>
            <el-form-item label="暂停容器数">
              <span>{{ props.row.detail.containersPaused }}</span>
            </el-form-item>
            <el-form-item label="镜像数">
              <span>{{ props.row.detail.images }}</span>
            </el-form-item>
            <el-form-item label="镜像占用空间">
              <span>{{ props.row.detail.imageMemSize }}</span>
            </el-form-item>
            <el-form-item label="网络数">
              <span>{{ props.row.detail.networkSize }}</span>
            </el-form-item>
            <el-form-item label="存储卷数">
              <span>{{ props.row.detail.volumeSize }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="自定义名称" min-width="55%" align="left" prop="name" />
      <el-table-column label="IP 地址" min-width="50%" align="left" prop="host" />
      <el-table-column label="TLS" min-width="20%" align="left" prop="tlsVerify">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.tlsVerify"/>
        </template>
      </el-table-column>
      <el-table-column label="证书路径" min-width="50%" align="left" prop="certPath" />
      <el-table-column label="API 版本" min-width="30%" align="left" prop="apiVersion" />      
      <el-table-column label="Docker 版本" min-width="35%" align="left" prop="dockerVersion" />
      <el-table-column label="操作系统" min-width="32%" align="left" prop="os" />
      <el-table-column label="PING" min-width="28%" align="left" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.docker_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="运行状态" min-width="30%" align="left" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.docker_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="*" align="left" lign="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['docker:config:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['docker:config:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改docker 信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="自定义名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入自定义名称" />
        </el-form-item>
        <el-form-item label="IP 地址" prop="host">
          <el-input v-model="form.host" placeholder="请输入 IP 地址" >
            <template slot="prepend">tcp://</template>
          </el-input>
        </el-form-item>
        <el-form-item label="TLS 验证">
          <el-radio-group v-model="form.tlsVerify">
            <el-radio
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="证书路径" prop="certPath">
          <el-input v-model="form.certPath" placeholder="请输入证书路径" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConfig, getConfig, delConfig, addConfig, updateConfig, getDetail } from "@/api/docker/config";

export default {
  name: "Config",
  dicts: ['sys_yes_no', 'docker_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // docker 信息表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        host: null,
        tlsVerify: null,
        status: null,
      },
      // 表单参数
      form: {
        id: null,
        name: null,
        host: null,
        tlsVerify: null,
        certPath: null
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "自定义名称不能为空", trigger: "blur" }
        ],
        host: [
          { required: true, message: "IP 地址不能为空", trigger: "blur" }
        ],
        tlsVerify: [
          { required: true, message: "TLS 验证不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询docker 信息列表 */
    getList() {
      this.loading = true;
      listConfig(this.queryParams).then(response => {
        response.data.map(item => {
          item.detail = [];
        });
        this.configList = response.data;
        this.total = response.total;
        this.loading = false;
      }).catch((r) => {
        this.loading = false;
        this.$modal.msgError(response.msg);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {}
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      getConfig(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConfig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$modal.confirm('是否确认删除编号为 "' + ids + '" 的数据项？').then(function() {
        return delConfig(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    async handledetail(row, expandedRows) {
      if (expandedRows.length > 0) {
        getDetail(row.id).then(response => {
          var data = response.data.result;
          var imageMemSize = parseFloat(response.data.imageMemSize / 1000000000).toFixed(3);
          var networkSize = response.data.networkSize;
          var volumeSize = response.data.volumeSize;
          var detail = {
            "name" : row.name,
            "localdomain" : data.Name,
            "cpu" : data.NCPU + ' 个',    
            "memTotal" : parseFloat(data.MemTotal / 1000000000).toFixed(2) + ' G',
            "operatingSystem" : data.OperatingSystem,
            "containers" : data.Containers + ' 个',
            "containersRunning" : data.ContainersRunning + ' 个',
            "containersPaused" : data.ContainersPaused + ' 个',
            "containersStopped" : data.ContainersStopped + ' 个',
            "containersPaused" : data.ContainersPaused + ' 个',
            "images" : data.Images + ' 个',
            "imageMemSize" : imageMemSize >= 1 ? imageMemSize + ' G' : imageMemSize + ' M',
            "networkSize" : networkSize + ' 个',
            "volumeSize" : volumeSize + ' 个',
            "mirrors" : data.RegistryConfig.Mirrors.join(', '),
          }
          this.configList.forEach((temp, index) => {
            if (temp.id === row.id) {
              this.configList[index].detail = detail;
            }
          });
      });
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('docker/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>

<style>
  .table-expand {
    font-size: 0;
  }
  .table-expand label {
    width: 80px;
    color: #99a9bf;
  }
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 25%;
  }
  .item {
    display: inline-block;
    vertical-align: middle;
  }
  .text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 250px; /* 超出150px后显示省略号 */
  }
</style>
